package com.xzone.material.user.service

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.xzone.material.user.dao.UserDao
import com.xzone.material.user.domain.entity.UserEntity
import com.xzone.material.user.domain.param.UserSaveParam
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service

@Service
class UserService(val userDao: UserDao, val passwordEncoder: PasswordEncoder) {
    fun findById(id: String): UserEntity? {
        return this.userDao.getById(id)
    }

    fun findByAccount(account: String): UserEntity? {
        val queryWrapper = KtQueryWrapper(UserEntity::class.java)
        queryWrapper.eq(UserEntity::account, account)
        return this.userDao.getOne(queryWrapper)
    }

    fun findByMobile(mobile: String): UserEntity? {
        val queryWrapper = KtQueryWrapper(UserEntity::class.java)
        queryWrapper.eq(UserEntity::mobile, mobile)
        return this.userDao.getOne(queryWrapper)
    }

    fun findByEmail(email: String): UserEntity? {
        val queryWrapper = KtQueryWrapper(UserEntity::class.java)
        queryWrapper.eq(UserEntity::email, email)
        return userDao.getOne(queryWrapper)
    }

    fun save(saveParam: UserSaveParam): UserEntity {
        val userEntity = UserEntity(
            nickname = saveParam.nickname,
            account = saveParam.account,
            mobile = saveParam.mobile,
            email = saveParam.email,
            password = passwordEncoder.encode(saveParam.password)
        )
        this.userDao.save(userEntity)
        return userEntity
    }
}